/**
 * 管理后台数据管理 Hook
 * 
 * 统一管理管理后台的数据获取和状态管理，避免重复API调用
 */

import { useState, useEffect, useCallback } from 'react'
import { adminApi } from '@/lib/api-client'

interface AdminStats {
  totalTools: number
  approvedTools: number
  pendingTools: number
  rejectedTools: number
  totalUsers: number
  totalReviews: number
  totalFavorites: number
}

interface Tool {
  id: string
  title: string
  description: string
  url: string
  status: 'PENDING' | 'APPROVED' | 'REJECTED'
  isDeployed: boolean
  deployPath?: string
  categoryId: string
  userId: string
  createdAt: string
  updatedAt: string
  category?: {
    id: string
    name: string
    icon: string
  }
  user?: {
    name: string
  }
  isExternal?: boolean
}

export function useAdminData() {
  const [tools, setTools] = useState<Tool[]>([])
  const [stats, setStats] = useState<AdminStats>({
    totalTools: 0,
    approvedTools: 0,
    pendingTools: 0,
    rejectedTools: 0,
    totalUsers: 0,
    totalReviews: 0,
    totalFavorites: 0
  })
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  // 获取工具数据
  const fetchTools = useCallback(async () => {
    try {
      setLoading(true)
      setError(null)
      
      const result = await adminApi.getTools()
      
      if (result.success) {
        const toolsData = (result.data || []).map((tool: any) => ({
          ...tool,
          isExternal: !tool.deployPath || tool.deployPath.trim() === ''
        }))
        
        setTools(toolsData)
        
        // 计算统计数据
        const newStats: AdminStats = {
          totalTools: toolsData.length,
          approvedTools: toolsData.filter(t => t.status === 'APPROVED').length,
          pendingTools: toolsData.filter(t => t.status === 'PENDING').length,
          rejectedTools: toolsData.filter(t => t.status === 'REJECTED').length,
          totalUsers: 0, // 这些需要单独的API
          totalReviews: 0,
          totalFavorites: 0
        }
        
        setStats(newStats)
      } else {
        setError(result.error || '获取工具数据失败')
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : '网络错误')
    } finally {
      setLoading(false)
    }
  }, [])

  // 获取完整统计数据（包括用户、评价、收藏）
  const fetchFullStats = useCallback(async () => {
    try {
      setLoading(true)
      setError(null)

      // 并行获取所有数据
      const [toolsResult, usersResult, reviewsResult, favoritesResult] = await Promise.all([
        adminApi.getTools(),
        adminApi.getUsers(),
        adminApi.getReviews(),
        adminApi.getFavorites()
      ])

      if (toolsResult.success) {
        const toolsData = (toolsResult.data || []).map((tool: any) => ({
          ...tool,
          isExternal: !tool.deployPath || tool.deployPath.trim() === ''
        }))
        
        setTools(toolsData)

        // 计算完整统计数据
        const newStats: AdminStats = {
          totalTools: toolsData.length,
          approvedTools: toolsData.filter(t => t.status === 'APPROVED').length,
          pendingTools: toolsData.filter(t => t.status === 'PENDING').length,
          rejectedTools: toolsData.filter(t => t.status === 'REJECTED').length,
          totalUsers: (usersResult.data || []).length,
          totalReviews: (reviewsResult.data || []).length,
          totalFavorites: (favoritesResult.data || []).length
        }
        
        setStats(newStats)
      } else {
        setError(toolsResult.error || '获取数据失败')
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : '网络错误')
    } finally {
      setLoading(false)
    }
  }, [])

  // 审核工具
  const approveTool = useCallback(async (toolId: string) => {
    try {
      const result = await adminApi.approveTool(toolId)
      if (result.success) {
        // 更新本地状态
        setTools(prev => prev.map(tool => 
          tool.id === toolId 
            ? { ...tool, status: 'APPROVED' as const }
            : tool
        ))
        
        // 更新统计数据
        setStats(prev => ({
          ...prev,
          pendingTools: prev.pendingTools - 1,
          approvedTools: prev.approvedTools + 1
        }))
        
        return { success: true }
      } else {
        return { success: false, error: result.error }
      }
    } catch (err) {
      return { 
        success: false, 
        error: err instanceof Error ? err.message : '审核失败' 
      }
    }
  }, [])

  // 拒绝工具
  const rejectTool = useCallback(async (toolId: string) => {
    try {
      const result = await adminApi.rejectTool(toolId)
      if (result.success) {
        // 更新本地状态
        setTools(prev => prev.map(tool => 
          tool.id === toolId 
            ? { ...tool, status: 'REJECTED' as const }
            : tool
        ))
        
        // 更新统计数据
        setStats(prev => ({
          ...prev,
          pendingTools: prev.pendingTools - 1,
          rejectedTools: prev.rejectedTools + 1
        }))
        
        return { success: true }
      } else {
        return { success: false, error: result.error }
      }
    } catch (err) {
      return { 
        success: false, 
        error: err instanceof Error ? err.message : '拒绝失败' 
      }
    }
  }, [])

  // 切换工具状态
  const toggleTool = useCallback(async (toolId: string, isDeployed: boolean) => {
    try {
      const result = await adminApi.toggleTool(toolId, isDeployed)
      if (result.success) {
        // 更新本地状态
        setTools(prev => prev.map(tool => 
          tool.id === toolId 
            ? { ...tool, isDeployed }
            : tool
        ))
        return { success: true }
      } else {
        return { success: false, error: result.error }
      }
    } catch (err) {
      return { 
        success: false, 
        error: err instanceof Error ? err.message : '操作失败' 
      }
    }
  }, [])

  // 初始化时获取数据
  useEffect(() => {
    fetchTools()
  }, [fetchTools])

  // 计算派生数据
  const pendingTools = tools.filter(tool => tool.status === 'PENDING')
  const approvedTools = tools.filter(tool => tool.status === 'APPROVED')
  const rejectedTools = tools.filter(tool => tool.status === 'REJECTED')

  return {
    // 数据
    tools,
    stats,
    pendingTools,
    approvedTools,
    rejectedTools,
    
    // 状态
    loading,
    error,
    
    // 操作
    fetchTools,
    fetchFullStats,
    approveTool,
    rejectTool,
    toggleTool,
    
    // 工具方法
    refreshData: fetchTools
  }
}
